package com.demo1;

import java.io.IOException;

import javax.servlet.AsyncContext;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;

public class MyReadListener implements ReadListener {
	private ServletInputStream input;
	private AsyncContext actx;
	public MyReadListener(ServletInputStream input, AsyncContext actx) {
		this.input = input;
		this.actx=actx;
	}
	@Override
	public void onDataAvailable() throws IOException {
		System.out.println("数据可用......");
		try {
			//暂停5秒，模拟业务执行
			Thread.sleep(5000);
			StringBuilder sb = new StringBuilder();
			int len = -1;
			byte [] buff = new byte[1024];
			//采用原始IO方式读取浏览器向Servlet提交的数据
			while(input.isReady() && (len=input.read(buff))!=-1 ){
				String data = new String(buff,0,len);
				sb.append(data);
			}
			System.out.println(sb);
			//将数据设置为request范围的属性
			actx.getRequest().setAttribute("info",sb);
			//转发到视图页面
			actx.dispatch("/async2.jsp");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	@Override
	public void onAllDataRead() throws IOException {
		System.out.println("数据读取完成");
	}
	@Override
	public void onError(Throwable e) {
		System.out.println("出现异常:"+e.getMessage());
	}

}
